/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.bitzer.google;

import com.google.gdata.client.finance.FinanceService;
import com.google.gdata.data.finance.PortfolioFeed;
import com.google.gdata.data.finance.PositionFeed;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.common.util.Base64;
import com.google.gdata.util.common.util.Base64DecoderException;
import java.net.URL;


/**
 *
 * @author fstech
 */

    public class Finance {

    private static Finance _instance  =   null;
    private static FinanceService service ;
    private static final String PORTFOLIO_FEED_URL_SUFFIX = "/portfolios";
    private static final String POSITION_FEED_URL_SUFFIX = "/positions?returns=true&transactions=false";
    private static final String PORTFOLIO_QUERY_STRING = "?returns=true&positions=true";
    public int recordCount  = 0;

    public static Finance instance(){
        if(_instance == null){
            _instance = new Finance();
        }
        return _instance;
    }

    public Finance(){
         
            service = new FinanceService(Constants.APPLICATION_NAME);
        
    }

    public void authenticate(String username, String password) throws AuthenticationException {

        if (username == null || password == null) {
            return;
        }
         service.setUserCredentials(username, password);
    }

   public PortfolioFeed getFeed(String lastModifiedOn, int startIndex, int numberOfRows) {

         PortfolioFeed portfolioFeed = null;
         String portfolioUrl = Constants.FINANCE_URL + PORTFOLIO_FEED_URL_SUFFIX + PORTFOLIO_QUERY_STRING;
         try {
             portfolioFeed = service.getFeed(new URL(portfolioUrl), PortfolioFeed.class);
             recordCount    =   portfolioFeed.getTotalResults();
             return portfolioFeed;
         } catch (Exception ex) {
             
             return null;
         }
    }

   public PositionFeed getPositionsFeed(String portfolioId){

       String id = null;
        try {
            id = new String(Base64.decode(portfolioId));
        } catch (Base64DecoderException ex) {

        }
       String positionsUrl = id+ POSITION_FEED_URL_SUFFIX;
       PositionFeed positionFeed = null;
       try {
           
           positionFeed = service.getFeed(new URL(positionsUrl), PositionFeed.class);
           recordCount    =   positionFeed.getTotalResults();
           
           return positionFeed;
       } catch (Exception ex) {
           return null;
       }

   }

   
}
